#include "model/model_dir.h"
#include "our_header.h"
#include "service/feature_7th.h"
#include <string.h>
// 登录验证，如果通过返回0;返回1，说明密码错误，-1用户名错误
// username:用户名
// passed:加密后密码
// token:返回的令牌
// dir_fd:返回的dir表的主键id
int loginVrify(MYSQL *conn, char username[], char passed[], char token[], int *dir_id) {
	USER_M user = {0};
	strcpy(user.name, username);
	strcpy(user.passwd, passed);
	int tag = verifyUser(conn, &user, dir_id);
	if(tag)
		return tag;
	getToken(user.name, token);
	// if(*dir_fd==-1)
	return 0;
}

// 使用此函数应先验证用户是否存在，然后传入用户名和加密后密码，和对应的盐值
int registUser(MYSQL *conn, char username[], char salt[], char passed[], int *dir_id) {
	USER_M user = {0};
	strcpy(user.name, username);
	strcpy(user.salt, salt);
	strcpy(user.passwd, passed);
	int user_id, tag;
	tag = insertUser(conn, &user, &user_id);
	if(tag)
		return tag;
	DIR_M dir = {0};
	dir.file_id = -1;
	dir.user_id = user_id;
	strcpy(dir.file_name, "~");
	dir.parent_id = -1;
	strcpy(dir.type, "d");
	strcpy(dir.path, "~");
	// char sql[512] = "insert into dir_7th(user_id,file_id,file_name,parent_id,type,path) value(?,?,?,?,?,?);";
	tag = insertDir(conn, &dir, dir_id);
	updateLastDir_idByName(conn, user.name, *dir_id);
	return tag;
}

// ls指令
int getDirList(MYSQL *conn, int cur_dir_id, dir_list_t *lists) {
	DIR_M *dirs;
	int tag = selectDirByparent_id_mul(conn, cur_dir_id, &dirs, &lists->size);
	if(tag) {
		return tag;
	}
	lists->item_head = calloc(lists->size, sizeof(dir_item_t));
	for(int i = 0; i < lists->size; i++) {
		strcpy(lists->item_head[i].file_name, dirs[i].file_name);
		strcpy(lists->item_head[i].type, dirs[i].type);
		lists->item_head[i].id = dirs[i].id;
	}
	free(dirs);
	return 0;
}

// pwd
int getPwd(MYSQL *conn, int cur_dir_id, char path[]) {
	DIR_M dir = {0};
	if(selectDirByid(conn, cur_dir_id, &dir) || strcmp(dir.type, "d"))
		return -1;
	strcpy(path, dir.path);
	return 0;
}

// cd 指令
int gotoDir(MYSQL *conn, int dir_id, char dest_path[], int *ret_dir_id, dir_list_t *lists) {
	DIR_M dir = {0};
	if(selectDirByid(conn, dir_id, &dir))
		return -1;
	char resul_path[1024] = {0};
	calDestPath(dir.path, dest_path, resul_path);
	if(strlen(resul_path)==0)
		return -1;
	if(getDir_idByPid_Path(conn, dir.user_id,resul_path,ret_dir_id))
		return -1;
	return getDirList(conn,*ret_dir_id,lists);
}